<template>
  <div class="app-container">
    <el-divider content-position="left"
      ><span class="head-divider">自留订单列表（）</span></el-divider
    >
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="商品名称" prop="queryGoodsName">
        <el-input
          v-model="queryParams.queryGoodsName"
          placeholder="模糊查询按商品名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="用户QQ号" prop="queryUsername">
        <el-input
          v-model="queryParams.queryUsername"
          placeholder="按QQ号码精准匹配"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="multiple"
          @click="handleZhuanApply"
          v-hasPermi="['business:goods:edit']"
          >批量转订单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />

      <el-table-column
        label="商品名称"
        align="center"
        width="300"
        prop="goodsName"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="购买人QQ账号"
        align="center"
        prop="username"
        width="150"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="价格"
        align="center"
        prop="orderPrice"
        width="100"
      />
      <el-table-column label="售卖数量" align="center" prop="sum" width="100" />
      <el-table-column
        label="商品所属画师"
        align="center"
        prop="painterName"
        width="120"
      />
      <el-table-column
        label="审核状态"
        align="center"
        prop="status"
        width="120"
      >
        <template #default="scope">
          <dict-tag :options="approveStatusList" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="订单备注"
        align="center"
        prop="remarks"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="200"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Switch"
            @click="handleZhuanApply(scope.row)"
            v-hasPermi="['business:goods:edit']"
            >转化订单</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:goods:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 选择商品 -->
    <el-dialog :title="title" v-model="open" width="580px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="painterId">
              <div v-if="!form.goodsName" class="txt-999">请选择商品名称</div>
              <div v-else>{{ form.goodsName }}</div>
              <el-button
                v-show="title == '新增'"
                class="btn"
                type="primary"
                @click="handleOpenModal"
                >选择</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="购买用户QQ" prop="username">
              <el-input v-model="form.username" placeholder="输入qq号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台" prop="platformId">
              <el-select
                v-model="form.platformId"
                placeholder="请选择"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="dict in platformList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格" prop="orderPrice">
              <el-input-number
                v-model="form.orderPrice"
                :min="0"
                :max="999999"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量" prop="sum">
              <el-input-number v-model="form.sum" :min="1" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="选择商品" v-model="openSub" width="80%" append-to-body>
      <Modal @change="handleGetSub" />
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { getSeckillListAll } from "@/api/goods/seckill";
import {
  listOrderSave,
  updateOrderSave,
  addOrderSave,
  approveOrderSave,
  delOrderSave,
} from "@/api/business/orderSave";
import { listPainter } from "@/api/business/painter";
import { listAllOrder } from "@/api/business/order";
import { useDebounceFn } from "@vueuse/core";
import { listPlatform } from "@/api/business/platform";

import Modal from "./modal.vue";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");

const pageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref(""); // 详情标题栏

const painterList = ref([]); // 画师下拉框
const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);
const approveStatusList = ref([
  {
    label: "已转成订单",
    value: "1",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "自留",
    value: "0",
    elTagClass: "",
    elTagType: "danger",
  },
]);

const statusList = ref([
  { label: "可以转让", value: 1 },
  { label: "禁止转让", value: 2 },
]);

const upStatusList = ref([
  { label: "上架", value: 1 },
  { label: "下架", value: 2 },
]);
const typeList = ref([
  { label: "限时", value: 0 },
  { label: "限量", value: 1 },
]);
const openSub = ref(false); // 查看购买详情
const openSub1 = ref(false); // 查看购买详情
const loadingSub = ref(false);
const pageListSub = ref([]);
const platformList = ref([]); // 平台下拉框

const data = reactive({
  stutasList: [
    {
      label: "上架",
      value: "1",
      elTagClass: "",
      elTagType: "success",
    },
    {
      label: "下架",
      value: "2",
      elTagClass: "",
      elTagType: "danger",
    },
  ],

  form: {
    upStatus: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryGoodsName: undefined,
    queryPainterName: undefined,
    orderType: undefined,
    orderName: undefined,
  },
  rules: {
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "change" },
    ],
    username: [{ required: true, message: "不能为空", trigger: "blur" }],
    orderPrice: [{ required: true, message: "不能为空", trigger: "blur" }],
    sum: [{ required: true, message: "不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules, stutasList } = toRefs(data);

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be PNG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
function onSuccessImg(response) {
  if (response.code == 200) {
    form.value.src = response.data;
    imageUrl.value = uploadShowUrl + response.data;
  }
}

/** 查询平台列表 */
function getPlatformList() {
  // loading.value = true;
  listPlatform().then((response) => {
    platformList.value = response.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    // loading.value = false;
  });
}
/** 查询画师列表 */
function getPainterList() {
  // loading.value = true;
  listPainter().then((response) => {
    painterList.value = response.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    // loading.value = false;
  });
}

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listOrderSave(queryParams.value).then((response) => {
    pageList.value = response.data.rows;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    goodsId: undefined,
    username: undefined,
    platformId: undefined,
    orderPrice: 0,
    sum: 1,
    remarks: "",
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.orderType = undefined;
  queryParams.value.orderName = undefined;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
/** 查看详情 */
function handleRead() {}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });

    form.value = {
      id: arr[0].id,
      goodsName: arr[0].goodsName,
      goodsId: arr[0].goodsId,
      platformId: arr[0].platformId,
      username: arr[0].username,
      orderPrice: arr[0].orderPrice,
      sum: arr[0].sum,
    };
  } else {
    form.value = {
      id: row.id,
      goodsName: row.goodsName,
      goodsId: row.goodsId,
      platformId: row.platformId,
      username: row.username,
      orderPrice: row.orderPrice,
      sum: row.sum,
    };
  }

  open.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateOrderSave(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrderSave(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }
  let arrList = pageList.value.filter((item) => {
    return;
  });
  proxy.$modal
    .confirm('是否确认删除编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return delOrderSave({ ids: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 查看购买详情 */
function handleOpenSub(row) {}

/** 转化订单按钮操作 */
function handleZhuanApply(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }

  proxy.$modal
    .confirm('是否确认转化编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return approveOrderSave({ ids: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("转化成功");
    })
    .catch(() => {});
}

function handleChangeType(params) {
  let arr = typeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}
// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
//
function handleOpenModal() {
  openSub.value = true;
}
// 获取选中商品的值
function handleGetSub(json) {
  openSub.value = false;
  data.form = {
    ...data.form,
    goodsName: json.goodsName,
    goodsId: json.id,
    price: json.price,
  };
}

getList();
getPlatformList();
// getPainterList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}
.avatar-uploader {
  width: 200px;
  height: 300px;
  .avatar {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.head-divider {
  font-size: 18px;
  font-weight: 600;
}
.btn {
  margin-left: 20px;
}
.txt-999 {
  color: #ccc;
}
</style>
